package com.spzx.auth.service;

import com.spzx.auth.form.RegisterBody;
import com.spzx.common.core.constant.CacheConstants;
import com.spzx.common.core.constant.Constants;
import com.spzx.common.core.constant.SecurityConstants;
import com.spzx.common.core.constant.UserConstants;
import com.spzx.common.core.domain.R;
import com.spzx.common.core.enums.UserStatus;
import com.spzx.common.core.exception.ServiceException;
import com.spzx.common.core.text.Convert;
import com.spzx.common.core.utils.StringUtils;
import com.spzx.common.core.utils.ip.IpUtils;
import com.spzx.common.redis.service.RedisService;
import com.spzx.common.security.utils.SecurityUtils;
import com.spzx.system.api.model.LoginUser;
import com.spzx.user.api.RemoteUserInfoService;
import com.spzx.user.api.domain.UpdateUserLogin;
import com.spzx.user.api.domain.UserInfo;
import io.micrometer.core.instrument.util.TimeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * ClassName: H5LoginService
 * Package: com.spzx.auth.service
 * Description:
 *
 * @Author ycy
 * @Create 2024/8/20 11:56
 * @Version 1.0
 */
@Component
@Service
public class H5LoginService {
    @Autowired
    private RemoteUserInfoService remoteUserInfoService;

    @Autowired
    private SysRecordLogService recordLogService;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private SysPasswordService passwordService;

    @Autowired
    private RedisService redisService;

    /**
     * 注册
     */
    public void register(RegisterBody registerBody) {
        String username = registerBody.getUsername();
        String password = registerBody.getPassword();
        String code = registerBody.getCode();
        String nickName = registerBody.getNickName();
        // 用户名或密码为空 错误
        if (StringUtils.isAnyBlank(username, password)) {
            throw new ServiceException("用户/密码必须填写");

        }

        if (username.length() != 11) {
            throw new ServiceException("账户长度必须为11个字符");
        }

        if (password.length() < UserConstants.PASSWORD_MIN_LENGTH || password.length() > UserConstants.PASSWORD_MAX_LENGTH) {
            throw new ServiceException("密码长度必须在5到20个字符之间");
        }

        if (StringUtils.isEmpty(code)) {
            throw new ServiceException("验证码不能为空");
        }

        String codeValue = redisTemplate.opsForValue().get("phone:code:" + username);

        if (!registerBody.getCode().equals(codeValue)) {
            throw new ServiceException("验证码不正确");
        }
        // 注册用户信息
        UserInfo userInfo = new UserInfo();
        userInfo.setUsername(username);
        nickName = StringUtils.isEmpty(nickName) ? username : nickName;
        userInfo.setNickName(nickName);

        userInfo.setPassword(SecurityUtils.encryptPassword(password));

        R<?> registerResult = remoteUserInfoService.register(userInfo, SecurityConstants.INNER);

        if (R.FAIL == registerResult.getCode()) {
            throw new ServiceException(registerResult.getMsg());
        }
        recordLogService.recordLogininfor(username, Constants.REGISTER, "注册成功");

    }


    /**
     * 登录
     *
     * @param username
     * @param password
     * @return
     */
    public LoginUser login(String username, String password) {

        // 用户名或者密码为空 错误
        if (StringUtils.isAnyBlank(username, password)) {
            recordLogService.recordLogininfor(username, Constants.LOGIN_FAIL, "用户名或密码不能为空");
            throw new ServiceException("用户名或密码不能为空");
        }
        // 密码不在指定范围内 错误
        if (password.length() < UserConstants.PASSWORD_MIN_LENGTH || password.length() > UserConstants.PASSWORD_MAX_LENGTH) {
            recordLogService.recordLogininfor(password, Constants.LOGIN_FAIL, "密码不在指定范围内");
            throw new ServiceException("密码不在指定范围内");
        }
        // 用户名不在指定范围内 错误
        if (username.length() < UserConstants.USERNAME_MIN_LENGTH || username.length() > UserConstants.USERNAME_MAX_LENGTH) {
            recordLogService.recordLogininfor(username, Constants.LOGIN_FAIL, "用户名不在指定范围内");
            throw new ServiceException("用户名不在指定范围内");
        }
        // IP 黑名单校验
        // 从 Redis 中获取黑名单 IP 列表的缓存对象，让后将缓存对象转化为字符串类型，将结果赋值给变量 blackStr
        String blackStr = Convert.toStr(redisService.getCacheObject(CacheConstants.SYS_LOGIN_BLACKIPLIST));

        if (IpUtils.isMatchedIp(blackStr, IpUtils.getIpAddr())) {
            recordLogService.recordLogininfor(username, Constants.LOGIN_FAIL, "访问IP已被列入黑名单");
            throw new ServiceException("访问IP已被列入黑名单");
        }

        // 查询用户信息
        R<UserInfo> userInfoR = remoteUserInfoService.getUserInfo(username,SecurityConstants.INNER);

        if (StringUtils.isNull(userInfoR) || StringUtils.isNull(userInfoR.getData())){
            recordLogService.recordLogininfor(username,Constants.LOGIN_FAIL,"登录用户不存在");
            throw new ServiceException("登录用户:" + username + "不存在");
        }

        if (R.FAIL == userInfoR.getCode()){
            throw new ServiceException(userInfoR.getMsg());
        }

        UserInfo userInfo = userInfoR.getData();
        LoginUser loginUser = new LoginUser();
        loginUser.setUserid(userInfo.getId());
        loginUser.setUsername(userInfo.getUsername());
        loginUser.setPassword(userInfo.getPassword());
        loginUser.setStatus(userInfo.getStatus() + "");

        if (UserStatus.DISABLE.getCode().equals(userInfo.getStatus())){
            recordLogService.recordLogininfor(username,Constants.LOGIN_FAIL,"用户已停用");
            throw new ServiceException("用户" + username + "已停用");
        }
        passwordService.validate(loginUser,password);
        recordLogService.recordLogininfor(username,Constants.LOGIN_SUCCESS,"登录成功");

        // 更新登录信息
        UpdateUserLogin updateUserLogin = new UpdateUserLogin();
        updateUserLogin.setUserId(userInfo.getId());
        updateUserLogin.setLastLoginIp(IpUtils.getIpAddr());
        updateUserLogin.setLastLoginTime(new Date());
        remoteUserInfoService.updateUserLogin(updateUserLogin,SecurityConstants.INNER);

        return loginUser;
    }
}
